package com.example.lab2;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.example.lab2.db.AppDBOpenHelper;
import com.example.lab2.db.Todolist;
import com.example.lab2.db.TodolistContract;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class TodolistAdapter extends RecyclerView.Adapter<ItemViewHolder> {
    private ArrayList<Todolist> things=new ArrayList<>();
    public static Context baseContext;
    public TodolistAdapter(){
    }
    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ItemViewHolder(LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recycleview_item,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
        holder.bind(things.get(position),this);
    }

    @Override
    public int getItemCount() {
        return things.size();
    }

    public void refresh(){
        AppDBOpenHelper dbOpenHelper=new AppDBOpenHelper(baseContext);
        SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
        Cursor cursor = db.query(TodolistContract.TodolistEntry.TABLENAME, null, null, null, null, null, null);
        things.clear();
        while (cursor.moveToNext()){
            things.add(new Todolist(cursor.getInt(cursor.getColumnIndex(TodolistContract.TodolistEntry.COL_NAME_ID)),
                    cursor.getString(cursor.getColumnIndex(TodolistContract.TodolistEntry.COL_NAME_DESCRIPTION)),
                    cursor.getString(cursor.getColumnIndex(TodolistContract.TodolistEntry.COL_NAME_DATE)),
                    cursor.getInt(cursor.getColumnIndex(TodolistContract.TodolistEntry.COL_NAME_STATE))
                    ));
        }
        notifyDataSetChanged();
    }
}
